/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.idea.maven.dom.converters

import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.text.VersionComparatorUtil
import com.intellij.util.xml.ConvertContext
import org.jetbrains.idea.maven.dom.converters.MavenConsumerPomUtil.getAutomaticParentVersion
import org.jetbrains.idea.maven.dom.converters.MavenConsumerPomUtil.isAutomaticVersionFeatureEnabled
import org.jetbrains.idea.maven.indices.MavenIndicesManager
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.server.MavenDistributionsCache
import org.jetbrains.idea.maven.utils.MavenUtil
import org.jetbrains.idea.reposearch.DependencySearchService
import java.util.regex.Pattern

class MavenArtifactCoordinatesVersionConverter : MavenArtifactCoordinatesConverter() {
  override fun fromString(s: String?, context: ConvertContext): String? {
    if (s != null) {
      return super.fromString(s, context)
    }

    if (isAutomaticVersionFeatureEnabled(context)) {
      return getAutomaticParentVersion(context)
    }
    return null
  }


  override fun doIsValid(id: MavenId, manager: MavenIndicesManager, context: ConvertContext): Boolean {
    if (StringUtil.isEmpty(id.groupId) || StringUtil.isEmpty(id.artifactId)) {
      return false
    }

    val path = context.file.containingDirectory?.virtualFile?.path
    val mavenVersion = path?.let { MavenUtil.getMavenVersion(context.project, it) } ?: MavenDistributionsCache.getInstance(
      context.project).settingsDistribution.version
    if (VersionComparatorUtil.compare(mavenVersion, "3.6.3") <= 0 && id.version == null) {
      return false
    }

    if (id.version == null) {
      return getAutomaticParentVersion(context) != null
    }

    if (id.version!!.isBlank()) {
      return false
    }

    if (MAGIC_VERSION_PATTERN.matcher(id.version!!).matches()) return true

    val projectsManager = MavenProjectsManager.getInstance(context.project)
    if (projectsManager.findProject(id) != null) return true

    // Check if artifact was found on importing.
    val projectFile = getMavenProjectFile(context)
    val mavenProject = if (projectFile == null) null else projectsManager.findProject(projectFile)
    if (mavenProject != null) {
      for (artifact in mavenProject.findDependencies(id)) {
        if (artifact.isResolved) {
          return true
        }
      }
    }

    val hasLocalVersion = manager.hasLocalVersion(id.groupId, id.artifactId, id.version)
    //MavenLog.LOG.trace("local index version $id: $hasLocalVersion")
    return hasLocalVersion
  }

  override fun doGetVariants(id: MavenId, searchService: DependencySearchService): Set<String> {
    // Do nothing. Completion variants are generated by MavenVersionCompletionContributor.
    return emptySet()
  }

  companion object {
    private val MAGIC_VERSION_PATTERN = Pattern.compile(
      "\\s*(?:LATEST|RELEASE|[(\\[].*|.*-20\\d{6}\\.[0-2]\\d{5}-\\d+)\\s*")
  }
}